package com.soriya.nestlive.service.common.impl;

import com.soriya.nestlive.service.common.UploadService;
import com.soriya.nestlive.util.excpetion.MyException;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@Service
public class UploadServiceImpl implements UploadService {

    @Override
    public String uploadImage(MultipartFile file) {
        return upload(file, "/nestlive_resource/image");
    }

    @Override
    public String uploadVideo(MultipartFile file) {
        return upload(file, "/nestlive_resource/source_video");
    }

    private String upload(MultipartFile file, String path) {
        String property = System.getProperty("user.dir").replaceAll("\\\\", "/");

        String currentMonth = new DateTime().toString("yyyyMM"); // 当前年月
        String prefix = UUID.randomUUID().toString().replaceAll("-", ""); // 文件名前缀
        String filename = file.getOriginalFilename();
        assert filename != null;
        String suffix = filename.substring(filename.lastIndexOf(".")); // 文件名后缀
        String key = String.format("%s/%s/%s%s", path, currentMonth, prefix, suffix); // 存储路径

        String filePath = property + key;

        try {
            InputStream inputStream = file.getInputStream();
            File f = new File(filePath);
            File mkdir = new File(filePath.substring(0, filePath.lastIndexOf("/")));
            if (!mkdir.isDirectory()) {
                boolean mkdirs = mkdir.mkdirs();
            }

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
            BufferedInputStream bis = new BufferedInputStream(inputStream);

            int i;
            byte[] bytes = new byte[1024 * 1024];
            while ((i = bis.read(bytes)) > 0) {
                bos.write(bytes, 0, i);
            }

            bis.close();
            bos.close();
        } catch (Exception e) {
            throw new MyException();
        }

//        return "https://www.enjoy-cloud.top:9001/static" + key;
//        return "http://127.0.0.1:8080/static" + key;
        return key;
    }

}
